package com.ruoyi.factory.qylock.utils;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.sign.Md5Utils;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName OkHttpUtils
 * @Description: TODO
 * @Author LiuJiaji
 * @Date 2023/5/9 0009 14:01
 **/
@Component
public class OkHttpUtils {

    @Value("${qys.sendUrl}")
    private String sendUrl;

    @Value("${qys.appToken}")
    private String appToken;

    @Value("${qys.appSecret}")
    private String appSecret;

    private static String hostSendUrl;

    private static String hostAppToken;

    private static String hostAppSecret;



    @PostConstruct
    public void getConfig(){
        hostSendUrl = this.sendUrl;
        hostAppToken = this.appToken;
        hostAppSecret = this.appSecret;
    }

    public  static String okHttpPost(String url,String json) {
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public  static String okHttpGet(String url, Map<String,String> param) {
        //拼接参数
        url = url + "?";
        for(String key:param.keySet()){
            url = url + key + "=" + param.get(key) + "&";
        }
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build(); //添加头部信息
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static String okHttpPostyxt(String url,String json,String token) {
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Authorization", token)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static String okHttpGetyxt(String url, Map<String,String> param,String token) {
        //拼接参数
        url = url + "?";
        for(String key:param.keySet()){
            url = url + key + "=" + param.get(key) + "&";
        }
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", token)
                .build(); //添加头部信息
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static String subimtFile(String url, Map<String,String> param) {
        Map<String,String> config = getconfigqys();
        String urlh = config.get("url");
        url = urlh+url;
        String signature = config.get("signature");
        String timestamp = config.get("timestamp");
        String accesstoken = config.get("accesstoken");

        String filePath = param.get("filePath");
        String fileName = param.get("fileName");
        String title = param.get("title");
        String fileType = param.get("fileType");
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File(filePath);
        long length = file.length();
        //封装文件格式
        MediaType mediaType = okhttp3.MediaType.parse("multipart/form-data");
        RequestBody fileBody = RequestBody.create(mediaType, file);//将file转换成RequestBody文件
        //文件内容
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//注意!需要在此处添加Content-Type
                .addFormDataPart("file", fileName, fileBody)
                .addFormDataPart("title", title)
                .addFormDataPart("fileType", fileType)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("x-qys-accesstoken", accesstoken)
                .addHeader("x-qys-timestamp", timestamp)
                .addHeader("x-qys-signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public  static String okHttpPostqys(String url,String param) {

        Map<String,String> config = getconfigqys();
        String urlh = config.get("url");
        url = urlh+url;
        String signature = config.get("signature");
        String timestamp = config.get("timestamp");
        String accesstoken = config.get("accesstoken");
        System.out.println("url: "+url);
        System.out.println("signature:"+signature);
        System.out.println("timestamp: "+timestamp);
        System.out.println("accesstoken: "+accesstoken);
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType,param);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("x-qys-accesstoken", accesstoken)
                .addHeader("x-qys-timestamp", timestamp)
                .addHeader("x-qys-signature", signature)
                .build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static Response okHttpGetqysxz(String url, Map<String,String> param) {
        Map<String,String> config = getconfigqys();
        String urlh = config.get("url");
        url = urlh+url;
        String signature = config.get("signature");
        String timestamp = config.get("timestamp");
        String accesstoken = config.get("accesstoken");
        //拼接参数
        url = url + "?";
        for(String key:param.keySet()){
            url = url + key + "=" + param.get(key) + "&";
        }
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-qys-accesstoken", accesstoken)
                .addHeader("x-qys-timestamp", timestamp)
                .addHeader("x-qys-signature", signature)
                .build(); //添加头部信息
        try {
            return okHttpClient.newCall(request).execute();
//            InputStream inputStream = response.body().byteStream();
//            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String okHttpGetqys(String url, Map<String,String> param) {
        Map<String,String> config = getconfigqys();
        String urlh = config.get("url");
        url = urlh+url;
        String signature = config.get("signature");
        String timestamp = config.get("timestamp");
        String accesstoken = config.get("accesstoken");
        //拼接参数
        url = url + "?";
        for(String key:param.keySet()){
            url = url + key + "=" + param.get(key) + "&";
        }
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-qys-accesstoken", accesstoken)
                .addHeader("x-qys-timestamp", timestamp)
                .addHeader("x-qys-signature", signature)
                .build(); //添加头部信息
        try {
            Response response = okHttpClient.newCall(request).execute();
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Map<String, String> getconfigqys(){

        long l = System.currentTimeMillis();
        String timestamp = String.valueOf(l);
        String signature = Md5Utils.hash(hostAppToken+hostAppSecret+timestamp);

        Map<String, String> config = new HashMap<>();
        config.put("accesstoken", hostAppToken);
        config.put("timestamp", timestamp);
        config.put("signature", signature);
        config.put("url", hostSendUrl);
        return config;
    }

    /**
     * 以post方式调用第三方接口方法.
     *
     * @param pathUrl     请求接口地址.
     * @param dataMap     请求参数.
     * @param accessToken accessToken.
     * @return str.
     */
    public static String doPostyxt(String pathUrl, String dataStr, String accessToken) {

        // 请求参数转换为json字符串
//        String dataStr = JSON.toJSONString(dataMap);
        String result = null;
        try {
            // 组装请求头信息
            Map<String, String> header = new HashMap<>(2);
            header.put("Content-Type", "application/json;charset=utf-8");
            if (accessToken != null && accessToken.length() > 0) {
                header.put("Authorization", accessToken);
            }
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
            RequestBody body = RequestBody.create(mediaType, dataStr);
            Request request = new Request.Builder()
                    .url(pathUrl)                   // 请求接口地址
                    .method("POST", body)   		// 设定请求的方法为"POST"
                    .headers(Headers.of(header))    // 请求头信息
                    .build();
            Response response = client.newBuilder().readTimeout(300000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
            result = Objects.requireNonNull(response.body().string());
        } catch (Exception e) {
            System.out.println("执行包含头部的post请求,url:" + pathUrl + "，请求数据:" + dataStr + ",执行错误信息:" + e);
        }
        return result;
    }

    /**
     * 以get方式调用第三方接口方法.
     *
     * @param pathUrl     请求接口地址.
     * @param accessToken accessToken.
     * @return str.
     */
    public static String doGet(String pathUrl, String accessToken) {

        String result = null;
        try {
            // 组装请求头信息
            Map<String, String> header = new HashMap<>(2);
            header.put("Content-Type", "application/json;charset=utf-8");
            if (accessToken != null && accessToken.length() > 0) {
                header.put("Authorization", accessToken);
            }
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            // http创建的request对象默认是get请求
            Request request = new Request.Builder()
                    .url(pathUrl)                   // 请求接口地址
                    .headers(Headers.of(header))    // 请求头信息
                    .build();
            Response response = client.newBuilder().readTimeout(300000L, TimeUnit.MILLISECONDS).build().newCall(request).execute();
            result = response.body().string();
        } catch (Exception e) {
            System.out.println("执行包含头部的get请求,url:" + pathUrl + ",执行错误信息:" + e);
        }
        return result;
    }


}

